package com.cy.improve.demos.web.elasticsearch;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {
    // URL and API key
    String serverUrl = "http://192.168.2.8:9200";


    @Bean
    public ElasticsearchClient client(@Autowired(required = false) JsonpMapper jsonpMapper, @Autowired(required = false) ObjectMapper objectMapper) {

        RestClient restClient = RestClient
                .builder(HttpHost.create(serverUrl))
                .setDefaultHeaders(new Header[]{
                })
                .build();


        ElasticsearchTransport transport = null;
        if (jsonpMapper != null) {
            transport = new RestClientTransport(restClient, jsonpMapper);
        } else if (objectMapper != null) {
            transport = new RestClientTransport(restClient, new JacksonJsonpMapper(objectMapper));
        } else {
            transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        }
        // Create the transport with a Jackson mapper


        // And create the API client
        return new ElasticsearchClient(transport);
    }


//    @Bean
//    public ElasticsearchClient elasticsearchClient (){
//        RestClient restClient = RestClient
//                .builder(HttpHost.create(serverUrl))
//                .setDefaultHeaders(new Header[]{
//                })
//                .build();
//
//         ElasticsearchTransport transport = new RestClientTransport(
//                restClient, new JacksonJsonpMapper());
//
//        return  new ElasticsearchClient(transport);
//    }
}
